from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime
from app.database.database import get_db
from app.models import models
from app.schemas import schemas

router = APIRouter(prefix="/api/storages", tags=["storages"])

@router.get("/", response_model=schemas.Page)
def get_storages(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=200), db: Session = Depends(get_db)):
    q = db.query(models.Storage)
    total = q.count()
    orm_items = q.offset((page-1)*size).limit(size).all()
    items = [schemas.Storage.model_validate(i) for i in orm_items]
    return {"total": total, "page": page, "size": size, "items": items}

@router.post("/", response_model=schemas.Storage)
def create_storage(storage: schemas.StorageCreate, db: Session = Depends(get_db)):
    obj = models.Storage(**storage.dict())
    db.add(obj); db.commit(); db.refresh(obj)
    return obj

@router.get("/{storage_id}", response_model=schemas.Storage)
def get_storage(storage_id: int, db: Session = Depends(get_db)):
    obj = db.query(models.Storage).filter(models.Storage.id == storage_id).first()
    if obj is None: raise HTTPException(status_code=404, detail="Storage not found")
    return obj

@router.put("/{storage_id}", response_model=schemas.Storage)
def update_storage(storage_id: int, storage: schemas.StorageCreate, db: Session = Depends(get_db)):
    obj = db.query(models.Storage).filter(models.Storage.id == storage_id).first()
    if obj is None: raise HTTPException(status_code=404, detail="Storage not found")
    for k,v in storage.dict().items(): setattr(obj, k, v)
    db.commit(); db.refresh(obj)
    return obj

@router.delete("/{storage_id}")
def delete_storage(storage_id: int, db: Session = Depends(get_db)):
    obj = db.query(models.Storage).filter(models.Storage.id == storage_id).first()
    if obj is None: raise HTTPException(status_code=404, detail="Storage not found")
    db.delete(obj); db.commit()
    return {"message": "Storage deleted successfully"}

@router.post("/bulk-delete")
def bulk_delete(ids: List[int], db: Session = Depends(get_db)):
    deleted = db.query(models.Storage).filter(models.Storage.id.in_(ids)).delete(synchronize_session=False)
    db.commit()
    return {"deleted": deleted}
